from google.appengine.ext import webapp
from web.constants import get_admin_user, title, slogan, menu, ARTICLES_ON_PAGE, \
    cleaner
from appengine_utilities import sessions
from web.models import ArticleModel, CommentModel, StatisticModel, \
    CommonStatisticModel, VersoinModel
from google.appengine.ext.webapp import template
import uuid
import os
from web.translate import translate
from datetime import datetime, timedelta
from sets import Set
from google.appengine.api import memcache

def get_stat_string():
    return "disabled" 
    stat_string = memcache.get("stats_string")
    if stat_string:
        return stat_string
    
    stats = CommonStatisticModel().all()
    stats.order("-date")
    stats.fetch(1)
    if stats.count() > 1:    
        value = stats[0].count
    else:
        value = 0
    memcache.add(key="stats_string", value=value, time=3600)
        
    return value
            
class SetVersion(webapp.RequestHandler):
    def get(self): 
        if not  get_admin_user():
            self.redirect("/version")
            return
                   
        version = self.request.get('version')
        if version:
            v = VersoinModel()
            v.version = version
            v.put()      
        self.redirect("/version")
    
class SubmitVersion(webapp.RequestHandler):
    def get(self):
        uuid = self.request.get('uuid')
        host = self.request.get('host')
        current_version = self.request.get('v')
        if uuid and host:
            find = StatisticModel().all()
            find.filter("userUUID", uuid)
            find.filter("host", host)
            find.filter("date", datetime.now().date())
            find.fetch(1)
            """if not hound uniq pc"""
            if find.count() == 0:
                nfind = CommonStatisticModel().all()                
                nfind.filter("date", datetime.now().date())
                nfind.fetch(1)
                if nfind.count() >= 1:
                    add = nfind[0]                
                    add.count += 1
                    add.put()    
                else:
                    add = CommonStatisticModel()                                                
                    add.put()

            model = StatisticModel()
            model.userUUID = uuid[:100]
            model.host = host[:100]
            model.v = current_version
            model.put()
              
        versions = VersoinModel.all()
        versions.order('-date')
        versions.fetch(1)    
        version = versions[0].version
        self.response.out.write(version)    

class RobotsTXT(webapp.RequestHandler):
    def post(self):
        self.get()
        
    def get(self):
        path = os.path.join(os.path.dirname(__file__), 'robots.txt')
        self.response.out.write(template.render(path, None))

class ShowStats(webapp.RequestHandler):
    def get(self):
        if not  get_admin_user():
            self.response.out.write("Not admin no statistsic")
            return None
        
        stats = CommonStatisticModel().all()
        stats.order("-date")
        for stat in stats:
            self.response.out.write(str(stat.date) + " <b>" + str(stat.count) + "</b><br/>");
        
        self.response.out.write("=================================<br/>");    
        
        current = datetime.today()
        today = datetime(current.year, current.month, current.day, 0, 0, 0, 0)        
        for i in xrange(3):            
            models = StatisticModel.all()
            
            host = self.request.get('host')
            if host:
                models.filter("host", host);
            models.order('-date')
            
            yesterday = today + timedelta(days= -i + 1)  
            be_yesterday = today + timedelta(days= -i)
            
            models.filter('date >', be_yesterday)
            models.filter('date <', yesterday)
            models.fetch(1000)
            
            set_uuid = Set()
            set_host = Set()        
            for model in models:
                set_uuid.add(model.userUUID)
                set_host.add(model.host)
                if host:
                    line = str(model.userUUID) + " : " + str(model.host) + " : <b>" + model.date.strftime("%d/%m/%Y") + "</b> </br>"
                    self.response.out.write(line)
            aver = (len(set_uuid) + len(set_host)) / 2   
            self.response.out.write("<br/><b>" + be_yesterday.strftime("%d/%m/%Y") + " </b>uuid: " + str(len(set_uuid)) + " hosts: " + str(len(set_host)) + " <b> " + str(aver) + "</b><br/>")
            for host in set_host:
                self.response.out.write("<a href='stats?host=" + str(host) + "'>" + str(host) + "</a>, ")
